﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Common;
using Common.Entities;
using Common.Models;
using OrderSales.Interface;
using OrderSales.Model;


namespace OrderSales.Presenter
{
    class SelectGoodsPresenter
    {
        private ISelectGoodsView _view;
        private List<Good> allGoods;
        private List<Good> filteredGoods;
        private Order _order;

        public SelectGoodsPresenter(ISelectGoodsView view, Order order)
        {
            _view = view;
            _order = order;
            allGoods = DataManager.GetInstance().Goods.GetGoodsIncludeAll();
            filteredGoods = allGoods;
            SetData();
            _view.ChangeFilter += FilteredData;
            _view.AddRecordOrder += AddRecordOrder;
        }

        private void SetData ()
        {
            _view.ListGoods = filteredGoods;
            _view.ListGroups = filteredGoods.OrderBy(good => good.Group.Name).Select(good => good.Group.Name).Distinct().ToList();
            _view.ListMarks = filteredGoods.OrderBy(good => good.TradeMark.Name).Select(good => good.TradeMark.Name).Distinct().ToList();
        }

        private void FilteredData(object o, EventArgs e)
        {
            List<Good> temp = allGoods;
            if (_view.IsFilterGoup)
            {
                temp = (temp.Where(good => good.Group.Name == _view.FilterGroup)).ToList();
            }
            if (_view.IsFilterMark)
            {
                temp = (temp.Where(good => good.TradeMark.Name == _view.FilterMark)).ToList();
            }
            filteredGoods = temp;
            SetData();
        }

        void AddRecordOrder (object sender, EventArgs e)
        {
            OrderRecord record = new OrderRecord();
            record.Good = filteredGoods[_view.SelectGoodIndex];
            record.Price =
                (double) (record.Good.GetType().GetProperty("Price" + _view.Price).GetValue(record.Good, null));
            record.Quantity = _view.Quantity;
            record.Amount = record.Price*record.Quantity;
            if (Settings.GetInstance().CheckRemainingGoods)
            {
                if (record.Quantity > record.Good.Remaining)
                    throw new Exception("Недостатньо товару");
            }
            DataManager.GetInstance().OrderRecords.InsertOrderRecord(record, _order.IdOrder);
        }
    }
}
